package com.rwb.springboot.sell.service.impl;

import com.rwb.springboot.sell.cenverter.OrderMaster2OrderDTOConverter;
import com.rwb.springboot.sell.dao.OrderDetailRepository;
import com.rwb.springboot.sell.dao.OrderMasterRepository;
import com.rwb.springboot.sell.dto.CartDTO;
import com.rwb.springboot.sell.dto.OrderDTO;
import com.rwb.springboot.sell.enums.OrderStatusEnum;
import com.rwb.springboot.sell.enums.PayStatusEnum;
import com.rwb.springboot.sell.enums.ResultEnum;
import com.rwb.springboot.sell.exception.MallException;
import com.rwb.springboot.sell.po.ProductInfo;
import com.rwb.springboot.sell.service.OrderService;
import com.rwb.springboot.sell.service.PayService;
import com.rwb.springboot.sell.service.ProductInfoService;
import com.rwb.springboot.sell.utils.KeyUtil;
import com.rwb.springboot.sell.vo.OrderDetail;
import com.rwb.springboot.sell.vo.OrderMaster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by ruwenbo on 2018/1/1.
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private PayService payService;

    @Override
    // 加事务，如果有异常之间的事务会回滚
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {

        // 订单Id
        String orderId = KeyUtil.getUniqueKey();
        // 总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        List<CartDTO> cartDTOList = new ArrayList<CartDTO>();

        if (orderDTO == null) {
            throw new MallException(ResultEnum.PARAM_EMPTY);
        }
        // 1.查询商品（数量,单价）
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            // 商品为空
            if (productInfo == null) {
                throw new MallException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            // 2.计算订单总价
            orderAmount = orderDetail.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmount);

            // 3.订单详情入库
            orderDetail.setDetailId(KeyUtil.getUniqueKey());
            orderDetail.setOrderId(orderId);
            // spring提供的属性拷贝
            BeanUtils.copyProperties(productInfo, orderDetail);
            OrderDetail detail = orderDetailRepository.save(orderDetail);
            if (detail == null) {
                throw new MallException(ResultEnum.DATA_EXCEPTION);
            }

            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity());
            cartDTOList.add(cartDTO);
        }

        // 4.插入数据库(OrderMaster和OrderDetail)
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        OrderMaster master = orderMasterRepository.save(orderMaster);
        if (master == null) {
            throw new MallException(ResultEnum.DATA_EXCEPTION);
        }

        // 4.如果下单成功扣库存
        productInfoService.decreaseStock(cartDTOList);

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {

        OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
        if (orderMaster == null) {
            throw new MallException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetails = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetails)) {
            throw new MallException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetails);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenId, Pageable pageable) {
        Page<OrderDTO> page = null;
        Page<OrderMaster> orderMasters = orderMasterRepository.findByBuyerOpenid(buyerOpenId, pageable);
        List<OrderDTO> orderDTOS = OrderMaster2OrderDTOConverter.converter(orderMasters.getContent());
        page = new PageImpl<OrderDTO>(orderDTOS, pageable, orderMasters.getSize());
        return page;
    }

    @Override
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
        // 判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            LOGGER.error("【取消订单】订单状态不正确,orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new MallException(ResultEnum.ORDER_STATUS_ERROR);
        }
        // 修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CHACEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            LOGGER.error("【取消订单】更新失败,orderMaster={}", updateResult);
            throw new MallException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        // 返回库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            LOGGER.error("【取消订单】订单中无商品详情,orderDTO={}", orderDTO);
            throw new MallException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = new ArrayList<CartDTO>();
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity());
            cartDTOList.add(cartDTO);

        }
        productInfoService.increaseStock(cartDTOList);

        // 如果客户已经支付需要退款给客户
        if (PayStatusEnum.SUCCESS.getCode().equals(orderDTO.getPayStatus())) {
            payService.refund(orderDTO);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO finish(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
        // 判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            LOGGER.error("【完结订单】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new MallException(ResultEnum.ORDER_STATUS_ERROR);
        }
        // 修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            LOGGER.info("【完结订单】更新订单失败,orderMaster={}", updateResult);
            throw new MallException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
        // 判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            LOGGER.error("【订单支付】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new MallException(ResultEnum.ORDER_STATUS_ERROR);
        }
        // 判断支付状态
        if (!PayStatusEnum.WAIT.getCode().equals(orderDTO.getPayStatus())) {
            LOGGER.error("【订单支付】支付状态不正确,orderDTO={}", orderDTO);
            throw new MallException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        // 修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            LOGGER.error("【订单支付】更新失败, orderMaster={}", orderMaster);
            throw new MallException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderDTO> page = null;
        Page<OrderMaster> orderMasters = orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOS = OrderMaster2OrderDTOConverter.converter(orderMasters.getContent());
        page = new PageImpl<OrderDTO>(orderDTOS, pageable, orderMasters.getSize());
        return page;
    }
}
